const { query, connect } = require('../model/index');
const ruleModel = require('../model/rule');
const groupModel = require('../model/group');
const adminModel = require('../model/admin');

/**
 * 查询权限列表
 * @param {} params 
 * @returns { list, pageCount }
 */
const getRuleList = async (params) => {
  const pageSize = Number(params.pageSize || 10);
  const pageNum = Number(params.pageNum || 1) - 1;
  const database = ruleModel.TABLE_NAME;
  let [rows, fields] = await connect.query(
    `select * from ${database} where status = ? order by id limit ? offset ?`,
    [1, pageSize, pageNum * pageSize]
  );
  let [countRows] = await connect.query(
    `select count(*) as count from ${database} where status = ?`,
    [1]
  );
  const pageCount = Math.ceil(countRows[0].count / pageSize); // 总页数

  return {
    list: rows,
    pageCount
  }
};

/**
 * 查询用户权限
 * @param {} params 
 * @returns { auth }
 */
const adminUserRules = async (params) => {
  const userId = params.id;
  const adminTable = adminModel.TABLE_NAME;
  const groupTable = groupModel.TABLE_NAME;
  
  let [auth] = await connect.query(
    `
    select
      a.id,a.group_id,b.rules
    from
      ${adminTable} as a
    left join ${groupTable} as b
    on
      a.group_id = b.id
    where
      a.id = ?
    `,
    [userId]
  );

  return {
    auth
  };
}

/**
 * 查询菜单下的权限
 * @param {*} params 
 * @returns 
 */
const ruleAuthById = async (params) => {
  const id = params.id;
  const database = ruleModel.TABLE_NAME;
  let [rows, fields] = await connect.query(
    `select * from ${database} where status = ? and pid = ?`,
    [1, id]
  );
  let [menuRows] = await connect.query(
    `select * from ${database} where status = ? and id = ?`,
    [1, id]
  );

  return {
    authList: rows,
    menuList: menuRows,
  }
}

module.exports = {
  getRuleList,
  adminUserRules,
  ruleAuthById
}